package com.boss.salary.controller;

import com.boss.api.dto.ApiResultDTO;
import com.boss.common.base.BasicinfoBaseController;
import com.boss.common.entity.PageDTO;
import com.boss.common.service.ICommonService;
import com.boss.common.util.PageUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.salary.entity.*;
import com.boss.salary.service.*;
import com.boss.salary.vo.AgencySalaryVO;
import com.boss.salary.vo.AgencyVerifyParamVo;
import com.boss.sys.ca.user.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/agencySalaryMultipleController")
public class AgencySalaryMultipleController extends BasicinfoBaseController {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(AgencySalaryMultipleController.class);

//    @Autowired
//    private IAgencySalaryMultipleService service;
    @Autowired
    private IAgencyInfoService agencyInfoService;
    @Autowired
    private IFormulaManageService formulaManageService;

    @Autowired
    private IGenerateSalaryDataService iGenerateSalaryDataService;

    @Autowired
    private ICommonService iCommonService;
    @Autowired
    private IAgencySalaryMultipleService service;

    @Autowired
    private IOperrateLogsService iOperrateLogsService;

    /**
     * 查询 工资项与机构挂接表分页
     * @param offset
     * @param limit
     * @return
     */
    @GetMapping("/queryAgencySalaryPage")
    public ApiResultDTO queryAgencySalaryPage(@RequestParam(value = "offset") String offset,
                                                 @RequestParam(value = "limit") String limit) {
        try {
            Map<String, Object> parameters = new HashMap<>(8);
            parameters.put("offset", offset);
            parameters.put("limit", limit);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTO(parameters);
            PageDTO<AgencySalary> pageDTO = service.queryAgencySalaryPage(paginationDTO);
            return ApiResultDTO.success(pageDTO);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 新增 工资项与机构挂接表
     * @param params 单位id和工资项id数组
     * @return
     */
    @PostMapping("/saveAgencySalary")
    public ApiResultDTO saveAgencySalary(@RequestHeader("tokenid") String tokenid,
                                        @RequestBody Map<String, Object> params) {
        try {
            String province = getUser(tokenid).getProvince();
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> agencyList = (List<Map<String, Object>>)params.get("agency");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> salaryList = (List<Map<String, Object>>)params.get("salary");
            String flag = params.get("flag").toString();
            service.saveAgencySalary(agencyList, salaryList, flag, province);
            return ApiResultDTO.success(null, "保存成功");
        } catch (Exception e) {
            logger.error("新增 工资项与机构挂接表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "新增 工资项与机构挂接表数据发生异常");
        }
    }

    /**
     * 更新 工资项与机构挂接表
     * @param agencySalary
     * @return
     */
    @PostMapping("/updateAgencySalary")
    public ApiResultDTO updateAgencySalary(@RequestBody AgencySalary agencySalary) {
        try {
            service.updateAgencySalary(agencySalary);
            return ApiResultDTO.success(null, "更新成功");
        } catch (Exception e) {
            logger.error("更新 工资项与机构挂接表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "修改 工资项与机构挂接表数据发生异常");
        }
    }

    /**
     * 删除 工资项与机构挂接表
     * @param id
     * @return
     */
    @DeleteMapping("/deleteAgencySalary/{id}")
    public ApiResultDTO deleteAgencySalary(@PathVariable("id") String id) {
        try {
            service.deleteAgencySalary(id);
            return ApiResultDTO.success(null, "删除成功");
        } catch (Exception e) {
            logger.error("删除 工资项与机构挂接表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "删除 工资项与机构挂接表数据发生异常");
        }
    }

    /**
     * 查询 工资项与机构挂接表 --不分页
     * @param agencyId
     * @return
     */
    @GetMapping("/queryAgencySalaryInfo")
    public ApiResultDTO queryAgencySalaryInfo(@RequestParam(value = "agencyId", required = false) String agencyId) {
        try {
            Map<String, Object> queryParam = new HashMap<>(1);
            queryParam.put("agencyId", agencyId);
            return ApiResultDTO.success(service.queryAgencySalaryInfo(queryParam),null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 分页查询 单位工资上报数据
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/queryUnitSalarySubmitReportPage")
    public ApiResultDTO queryUnitSalarySubmitReportPage(@RequestHeader("tokenid") String tokenid,
                                                  @RequestParam(value = "page") String page,
                                                  @RequestParam(value = "limit") String limit,
                                                  @RequestParam(value = "agencyId") String agencyId,
                                                  @RequestParam(value = "flag") String flag,
                                                  @RequestParam(value = "menuid") String menuid,
                                                  @RequestParam(value = "salaryMonth", required = false) String salaryMonth,
                                                  @RequestParam(value = "changes", required = false) String changes,
                                                  @RequestParam(value = "personType", required = false) String personType,
                                                  @RequestParam(value = "salaryType", required = false) String salaryType,
                                                  @RequestParam(value = "personName", required = false) String personName,
                                                  @RequestParam(value = "idenNo", required = false) String idenNo){
        try{
            UserDTO userDTO = getUser(tokenid);
            Map<String, Object> queryParam = new HashMap<>(7);
            queryParam.put("agencyId", agencyId);
            queryParam.put("flag", flag);
            queryParam.put("salaryMonth", salaryMonth);
            queryParam.put("changes", changes);
            queryParam.put("personType", personType);
            queryParam.put("salaryType", salaryType);
            queryParam.put("personName", personName);
            queryParam.put("idenNo", idenNo);
            queryParam.put("menuid", menuid);
            queryParam.put("mofDivCode", userDTO.getProvince());
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            PageDTO<Map<String,Object>> pageDTO = service.getUnitSalarySubmitReportPage(userDTO, paginationDTO, queryParam);
            return ApiResultDTO.success(pageDTO);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 单位上报查询上报工资额
     * @param tokenid
     * @param menuid
     * @param agencyId
     * @param flag
     * @param salaryMonth
     * @param changes
     * @param personType
     * @param salaryType
     * @param personName
     * @param idenNo
     * @return
     */
    @GetMapping("/selectSubmitSalarySum")
    public ApiResultDTO selectSubmitSalarySum(@RequestHeader("tokenid") String tokenid,
                                              @RequestParam(value = "menuid") String menuid,
                                              @RequestParam(value = "agencyId") String agencyId,
                                              @RequestParam(value = "flag") String flag,
                                              @RequestParam(value = "salaryMonth", required = false) String salaryMonth,
                                              @RequestParam(value = "changes", required = false) String changes,
                                              @RequestParam(value = "personType", required = false) String personType,
                                              @RequestParam(value = "salaryType", required = false) String salaryType,
                                              @RequestParam(value = "personName", required = false) String personName,
                                              @RequestParam(value = "idenNo", required = false) String idenNo){
        try{
            UserDTO userDTO = getUser(tokenid);
            Map<String, Object> queryParam = new HashMap<>(2);
            queryParam.put("agencyId", agencyId);
            queryParam.put("flag", flag);
            queryParam.put("salaryMonth", salaryMonth);
            queryParam.put("changes", changes);
            queryParam.put("personType", personType);
            queryParam.put("salaryType", salaryType);
            queryParam.put("personName", personName);
            queryParam.put("idenNo", idenNo);
            queryParam.put("menuid", menuid);
            String sum = service.selectSubmitSalarySum(userDTO, queryParam);
            return ApiResultDTO.success(sum);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 分页查询 单位工资编报数据
     * @param page 页码
     * @param limit 行数
     * @param flag 判断tab页
     * @param agencyId 机构ID
     * @param condition 查询条件
     * @return
     */
    @GetMapping("/queryUnitSalaryReportPage")
    public ApiResultDTO queryUnitSalaryReportPage(@RequestHeader("tokenid") String tokenid,
                                                  @RequestParam(value = "page") String page,
                                                  @RequestParam(value = "limit") String limit,
                                                  @RequestParam(value = "flag") String flag,
                                                  @RequestParam(value = "agencyId") String agencyId,
                                                  @RequestParam Map<String,Object> condition) {
        try{
            UserDTO userDTO = getUser(tokenid);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            PageDTO<Map<String,Object>> pageDTO = service.getUnitSalaryReportPage(paginationDTO, agencyId, flag, condition,userDTO.getProvince());
            return ApiResultDTO.success(pageDTO);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 查询工资变动人数
     * @param agencyId 机构ID
     * @param salaryType
     * @return
     */
    @GetMapping("/selectSalaryChangePersonNum")
    public ApiResultDTO selectSalaryChangePersonNum(@RequestHeader("tokenid") String tokenid,
                                                    @RequestParam(value = "agencyId") String agencyId,
                                                    @RequestParam(value = "isThirteen") String isThirteen,
                                                  @RequestParam(value = "salaryType") String salaryType) {
        try{
            UserDTO userDTO = getUser(tokenid);
            Map<String, Object> queryParam = new HashMap<>(2);
            queryParam.put("agencyId", agencyId);
            queryParam.put("salaryType", salaryType);
            int personNum = service.selectSalaryChangePersonNum(userDTO,agencyId,isThirteen, queryParam,1);
            return ApiResultDTO.success(personNum, "查询工资变动人数成功");
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }
    /**
     * 分页查询 单位审核数据
     * @param page 页码
     * @param limit 行数
     * @param flag 判断tab页
     * @param agencyId 机构ID
     * @param condition 查询条件
     * @return
     */
    @GetMapping("/queryUnitAuditPage")
    public ApiResultDTO queryUnitAuditPage(@RequestHeader("tokenid") String tokenid,
                                           @RequestParam(value = "page") String page,
                                           @RequestParam(value = "limit") String limit,
                                           @RequestParam(value = "flag") String flag,
                                           @RequestParam(value = "agencyId") String agencyId,
                                           @RequestParam(value = "menuid") String menuid,
                                           @RequestParam Map<String,Object> condition) {
        try{
            UserDTO userDTO = getUser(tokenid);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            PageDTO<Map<String,Object>> pageDTO = service.getUnitAuditPage(paginationDTO, agencyId, flag, condition,userDTO,menuid);
            return ApiResultDTO.success(pageDTO);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 分页查询 单位审核数据
     * @param page 页码
     * @param limit 行数
     * @param flag 判断tab页
     * @param agencyId 机构ID
     * @param condition 查询条件
     * @return
     */
    @GetMapping("/queryFinancialAuditSalaryPage")
    public ApiResultDTO queryFinancialAuditSalaryPage(@RequestHeader("tokenid") String tokenid,
                                           @RequestParam(value = "page") String page,
                                           @RequestParam(value = "limit") String limit,
                                           @RequestParam(value = "flag") String flag,
                                           @RequestParam(value = "agencyId") String agencyId,
                                           @RequestParam Map<String,Object> condition) {
        try{
            UserDTO userDTO = getUser(tokenid);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            PageDTO<Map<String,Object>> pageDTO = service.getFinancialAuditSalaryPage(paginationDTO, agencyId, flag, condition,userDTO.getProvince());
            return ApiResultDTO.success(pageDTO);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 动态查询工资编报表头
     * @param agencyId
     * @return
     */
    @GetMapping("/queryColumnName")
    public ApiResultDTO queryColumnName(@RequestHeader("tokenid") String tokenid,@RequestParam(value = "agencyId") String agencyId,@RequestParam Map<String,Object> condition){
        try{
            UserDTO userDTO = getUser(tokenid);
            List<String> columnNameList = service.getColumnName(agencyId,condition,userDTO);
            return ApiResultDTO.success(columnNameList);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 获取实发工资总和和机构总人数
     * @param agencyId
     * @return
     */
    @GetMapping("/queryReallySendSalarySumAndPersonTotal")
    public ApiResultDTO queryReallySendSalarySumAndPersonTotal(@RequestParam("agencyId") String agencyId,
                                                               @RequestParam("isThirteen") String isThirteen,
                                                               @RequestParam(value = "salaryType", required = false) String salaryType){
        try{
            Map<String, String> result = service.getReallySendSalarySumAndPersonTotal(agencyId, isThirteen, salaryType);
            return ApiResultDTO.success(result);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 获取上报的实发工资总和和机构总人数
     * @param agencyId
     * @return
     */
    @GetMapping("/querySubmitReallySendSalarySumAndPersonTotal")
    public ApiResultDTO querySubmitReallySendSalarySumAndPersonTotal(@RequestParam("agencyId") String agencyId,
                                                                     @RequestParam("isThirteen") String isThirteen,
                                                               @RequestParam("queryThirteen") Integer queryThirteen,
                                                               @RequestParam(value = "salaryType", required = false) String salaryType){
        try{
            Map<String, String> result = service.querySubmitReallySendSalarySumAndPersonTotal(agencyId,isThirteen, queryThirteen, salaryType);
            return ApiResultDTO.success(result);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 获取金额计算公式
     */
    @GetMapping("/generateFormula")
    public ApiResultDTO generateFormula(@RequestHeader("tokenid") String tokenid,
                                        @RequestParam(value = "agencyId") String agencyId){
        try{
            UserDTO userDTO = getUser(tokenid);
            List<FormulaManage> formulaList = formulaManageService.generateFormula(userDTO,agencyId);
            return ApiResultDTO.success(formulaList);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 字段对应工资名称字典
     * @param agencyId
     * @return
     */
    @GetMapping("/querySalaryName")
    public ApiResultDTO querySalaryName(@RequestHeader("tokenid") String tokenid,@RequestParam(value = "agencyId") String agencyId,@RequestParam Map<String,Object> condition){
        try{
            UserDTO userDTO = getUser(tokenid);
            List<Map<String,Object>> columnNameList = service.getSalaryName(userDTO.getProvince());
            return ApiResultDTO.success(columnNameList);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 编报
     * @param data
     * @return
     */
    @PostMapping("/submitUnitSalaryReportData")
    public ApiResultDTO submitUnitSalaryReportData(@RequestHeader("tokenid") String tokenid,
                                                   @RequestBody List<SalaryMonthEnd> data){
        try{
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("单位工资编报--单位工资编报--修改工资");

            ArrayList<Object> personIds = new ArrayList<>();

            for (SalaryMonthEnd monthEnd : data) {
                operrateLogs.setAgencyId(monthEnd.getAgencyId());
                personIds.add(monthEnd.getPersonId());
            }

            String personid= org.apache.commons.lang.StringUtils.join(personIds,",");
            operrateLogs.setPersonId(personid);
            iOperrateLogsService.saveOperrateLogs(operrateLogs);
           /* for (SalaryMonthEnd datum : data) {
                datum.setMofDivCode(userDto.getProvince());
            }*/
            service.saveUnitSalaryReport(data,userDto);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "保存 单位工资编报数据发生异常");
        }
    }

    /**
     * 工资编报送审（以机构为单位送审）
     * @param agencyVerifyParamVo
     * @return
     */
    @PostMapping("/submitUnitSalaryReport")
    public ApiResultDTO submitUnitSalaryReport(@RequestHeader("tokenid") String tokenid,
                                               @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){
        try{
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("单位工资编报--单位工资编报--报送财务审核");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);


            service.submitUnitSalaryReport(agencyVerifyParamVo, userDto);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "送审发生异常");
        }
    }



    /**
     * 撤销工资编报送审
     * @param agencyVerifyParamVo 机构ID
     * @return
     */
    @PostMapping("/rejectSubmitUnitSalaryReport")
    public ApiResultDTO rejectSubmitUnitSalaryReport(@RequestHeader("tokenid") String tokenid,
                                                     @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){
        try{
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("单位工资编报--单位工资编报--撤销送审");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            service.rejectSubmitUnitSalaryReport(agencyVerifyParamVo, userDto);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 工资编报送审（以机构为单位送审-一岗送财政）
     * @param agencyVerifyParamVo
     * @return
     */
    @PostMapping("/submitUnitSalaryReportOne")
    public ApiResultDTO submitUnitSalaryReportOne(@RequestHeader("tokenid") String tokenid,
                                                  @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){
//        boolean flag=true;
//        //是否校验月份，预警月份为0时该值为false
//        String months="0";
//        //预警月份大与1的校验结果
//        boolean monthflag=true;
        Map<String,Object> remap=new HashMap<>();
        try{

//            AgencyInfo agency=agencyInfoService.getNameById(agencyVerifyParamVo.getAgencyId());
            List<String> agencyids=new ArrayList<>();
            agencyids.add(agencyVerifyParamVo.getAgencyId());
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("单位工资编报--单位工资编报--报送财务审核");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            remap=service.auditUnitAuditInCommit(agencyids,agencyVerifyParamVo,userDto,true,tokenid);
            if(!StringUtils.isEmpty(remap.get(ERROR_RSCODE))){
                return ApiResultDTO.error(ERROR_RSCODE, remap.get(ERROR_RSCODE).toString());
            }
            return ApiResultDTO.success(remap.get("100000"));
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "送审发生异常");
        }
    }
    /**
     * 撤销工资编报送审(一岗送财政撤销)
     * @param agencyVerifyParamVo 机构ID
     * @return
     */
    @PostMapping("/rejectSubmitUnitSalaryReportOne")
    public ApiResultDTO rejectSubmitUnitSalaryReportOne(@RequestHeader("tokenid") String tokenid,
                                                     @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){
        try{
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("单位工资编报--单位工资编报--撤销送审");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            service.rejectSubmitUnitSalaryReportOne(agencyVerifyParamVo, userDto);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销送审发生异常");
        }
    }

    /**
     * 撤销修改
     * @param data
     * @return
     */
    @PostMapping("/rejectEditUnitSalaryReport")
    public ApiResultDTO rejectEditUnitSalaryReport(@RequestHeader("tokenid") String tokenid,
                                                   @RequestBody SalaryMonthEnd data){
        try{
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("单位工资编报--单位工资编报--撤销工资修改");
            operrateLogs.setAgencyId(data.getAgencyId());
            operrateLogs.setPersonId(data.getPersonId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            service.rejectEditUnitSalaryReport(userDto.getProvince(), data);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销修改发生异常");
        }
    }

    /**
     * 审核(单位工资审核中间岗)
     * @param agencyVerifyParamVo
     * @return
     */
    @PostMapping("/auditUnitAuditMiddle")
    public ApiResultDTO auditUnitAuditMiddle(@RequestHeader("tokenid") String tokenid,
                                       @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){


        try{
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("财务审核--工资审核--审核");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            service.auditUnitAuditMiddle(agencyVerifyParamVo, userDto);//单位中间岗审核通过

            return ApiResultDTO.success("审核成功！");
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "审核发生异常");
        }
    }

    /**
     * 审核
     * @param agencyVerifyParamVo
     * @return
     */
    @PostMapping("/auditUnitAudit")
    public ApiResultDTO auditUnitAudit(@RequestHeader("tokenid") String tokenid,
                                       @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){
        String success="100000";
//        boolean flag=true;
//        //是否校验月份，预警月份为0时该值为false
//        String months="0";
//        //预警月份大与1的校验结果
//        boolean monthflag=true;
        Map<String,Object> remap=new HashMap<>();
        try{
//            AgencyInfo agency=agencyInfoService.getNameById(agencyVerifyParamVo.getAgencyId());
            List<String> agencyids=new ArrayList<>();
            agencyids.add(agencyVerifyParamVo.getAgencyId());
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("财务审核--审核上报--审核并上报");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);
//            try{
//                remap= iGenerateSalaryDataService.isPaymentEnough(agencyids,userDto);//校验指标是否满足工资发放
//                flag="true".equals(remap.get("isEnough"));
//                //是否校验月份，预警月份为0时该值为false
//                months=remap.get("months");
//                //预警月份大与1的校验结果
//                monthflag="true".equals(remap.get("isMonthsEnough"));
//            }catch(Exception e){
//                logger.error(e.getMessage(), e);
//                return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
//            }
//            if(flag){
//                StringBuffer res=new StringBuffer();
//
//                service.auditUnitAudit(agencyVerifyParamVo, userDto);//审核通过，并上报
//                res.append("审核并上报成功！");
//                if(!"0".equals(months)&&!"1".equals(months)&&!monthflag){
//                    res.append("但工资指标不足已发放").append(months).append("个月");
//                    iCommonService.pushMessageToApaas(userDto,agencyVerifyParamVo.getAgencyId(),
//                            agency.getAgencyCode()+"-"+agency.getAgencyName()+"工资指标余额不够发放"+months+"个月");
//                }
//                return ApiResultDTO.success(res.toString());
//            }else{
//                iCommonService.pushMessageToApaas(userDto,agencyVerifyParamVo.getAgencyId(),
//                        agency.getAgencyCode()+"-"+agency.getAgencyName()+"工资指标余额不足");
//                return ApiResultDTO.error(ERROR_RSCODE, "指标余额不足！");
//            }
            remap=service.auditUnitAuditInCommit(agencyids,agencyVerifyParamVo,userDto,false,tokenid);
            if(!StringUtils.isEmpty(remap.get(ERROR_RSCODE))){
                 return ApiResultDTO.error(ERROR_RSCODE, remap.get(ERROR_RSCODE).toString());
            }
            return ApiResultDTO.success(remap.get(success));
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "审核发生异常");
        }
    }

    /**
     * 撤销
     * @param agencyVerifyParamVo
     * @return
     */
    @PostMapping("/rejectAuditUnitAudit")
    public ApiResultDTO rejectAuditUnitAudit(@RequestHeader("tokenid") String tokenid,
                                             @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){
        try{
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("财务审核--单位上报--撤销审核");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            service.rejectAuditUnitAudit(agencyVerifyParamVo, userDto);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 撤销单位中间岗撤销
     * @param agencyVerifyParamVo
     * @return
     */
    @PostMapping("/rejectAuditUnitAuditMiddle")
    public ApiResultDTO rejectAuditUnitAuditMiddle(@RequestHeader("tokenid") String tokenid,
                                             @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){
        try{
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("财务审核--单位审核--撤销审核");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            service.rejectAuditUnitAuditMiddle(agencyVerifyParamVo, userDto);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 退回
     * @param tokenid
     * @param agencyVerifyParamVo
     * @return
     */
    @PostMapping("/returnedUnitAudit")
    public ApiResultDTO returnedUnitAudit(@RequestHeader("tokenid") String tokenid,
                                          @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){
        try{
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("财务审核--审核上报--退回");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            service.returnedUnitAudit(agencyVerifyParamVo, userDto);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "退回发生异常");
        }
    }

    @PostMapping("/rejectReturnedUnitAudit/{agencyId}")
    public ApiResultDTO rejectReturnedUnitAudit(@RequestHeader("tokenid") String tokenid,@PathVariable("agencyId") String agencyId){
        try{
            UserDTO userDto = getUser(tokenid);
            service.rejectReturnedUnitAudit(agencyId,userDto);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销退回发生异常");
        }
    }

    @GetMapping("/queryReturnedState")
    public ApiResultDTO queryReturnedState(@RequestParam(value = "agencyId") String agencyId){
        try{
            boolean flag = service.getReturnedState(agencyId);
            return ApiResultDTO.success(flag);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 档案查询--获取单位下人员的工资信息
     * @param agencyId
     * @param personId
     * @return
     */
    @GetMapping("/getPersonSalaryInfo")
    public ApiResultDTO getPersonSalaryInfo(@RequestHeader("tokenid") String tokenid,
                                            @RequestParam(value = "agencyId") String agencyId,
                                            @RequestParam(value = "personId") String personId,
                                            @RequestParam(value = "personType") String personType ){
        try{
            List<String> personTypes=new ArrayList<>();
            if(!StringUtils.isEmpty(personType)) {
                personTypes.add(personType);
            }
            UserDTO userDto = getUser(tokenid);
            List<Map<String,Object>> result = service.getPersonSalaryInfo(agencyId, personId,personTypes,userDto.getProvince());
            return ApiResultDTO.success(result);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 档案查询--获取单位下人员的工资信息
     * @param agencyId
     * @param personId
     * @return
     */
    @GetMapping("/getSalaryMonthEedSubmit")
    public ApiResultDTO getSalaryMonthEedSubmit(@RequestHeader("tokenid") String tokenid,
                                            @RequestParam(value = "agencyId") String agencyId,
                                            @RequestParam(value = "personId") String personId,
                                            @RequestParam(value = "personType") String personType ){
        try{
            List<String> personTypes=new ArrayList<>();
            if(!StringUtils.isEmpty(personType)) {
                personTypes.add(personType);
            }
            UserDTO userDto = getUser(tokenid);
            List<Map<String,Object>> result = service.getSalaryMonthEedSubmit(agencyId, personId,personTypes,userDto.getProvince());
            return ApiResultDTO.success(result);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 十三月工资：动态表头
     * @param agencyId
     * @return
     */
    @GetMapping("/queryColumnByAgencyId")
    public ApiResultDTO queryColumnByAgencyId(@RequestHeader("tokenid") String tokenid,@RequestParam(value = "agencyId") String agencyId){
        try{
            UserDTO userDto = getUser(tokenid);
            List<AgencySalaryVO> columnNameList = service.getColumnByAgencyId(userDto);
            return ApiResultDTO.success(columnNameList);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }
    /**
     * 获取单位编报送审状态
     * @return
     */
    @GetMapping("/getSalaryState")
    public ApiResultDTO getSalaryState(@RequestParam(value = "agencyId") String agencyId){
        try {
            Map<String, Object> salaryState = service.getSalaryState(agencyId);
            return ApiResultDTO.success(salaryState);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 单位工资编报：验证是否存在未上传附件人员
     * @param agencyId
     * @return
     */
    @GetMapping("/verfityExistNoFilePerson")
    public ApiResultDTO verfityExistNoFilePerson(@RequestParam("agencyId") String agencyId){
        try {
            boolean flag = service.verfityExistNoFilePerson(agencyId);
            return ApiResultDTO.success(flag);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 批量审核.
     * @param agencyVerifyParamVo
     * @return
     */
    @PostMapping("/batchAuditUnitAudit")
    public ApiResultDTO batchAuditUnitAudit(@RequestHeader("tokenid") String tokenid,
                                            @RequestBody AgencyVerifyParamVo agencyVerifyParamVo){
        String success="100000";
        String id = "";
        id = agencyVerifyParamVo.getAgencyId();

        AgencyInfo agencyInfo = agencyInfoService.getNameById(id);
//        boolean flag=true;
//        //是否校验月份，预警月份为0时该值为false
//        String months="0";
//        //预警月份大与1的校验结果
//        boolean monthflag=true;
        Map<String,Object> remap=new HashMap<>();
        try{
//            AgencyInfo agency=agencyInfoService.getNameById(agencyVerifyParamVo.getAgencyId());
            List<String> agencyids=new ArrayList<>();
            agencyids.add(agencyVerifyParamVo.getAgencyId());
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("财务审核--审核上报--审核并上报");
            operrateLogs.setAgencyId(agencyVerifyParamVo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);
//            try{
//                remap= iGenerateSalaryDataService.isPaymentEnough(agencyids,userDto);//校验指标是否满足工资发放
//                flag="true".equals(remap.get("isEnough"));
//                //是否校验月份，预警月份为0时该值为false
//                months=remap.get("months");
//                //预警月份大与1的校验结果
//                monthflag="true".equals(remap.get("isMonthsEnough"));
//            }catch(Exception e){
//                logger.error(e.getMessage(), e);
//                return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
//            }
//            if(flag){
//                StringBuffer res=new StringBuffer();
//
//                service.auditUnitAudit(agencyVerifyParamVo, userDto);//审核通过，并上报
//                res.append("审核并上报成功！");
//                if(!"0".equals(months)&&!"1".equals(months)&&!monthflag){
//                    res.append("但工资指标不足已发放").append(months).append("个月");
//                    iCommonService.pushMessageToApaas(userDto,agencyVerifyParamVo.getAgencyId(),
//                            agency.getAgencyCode()+"-"+agency.getAgencyName()+"工资指标余额不够发放"+months+"个月");
//                }
//                return ApiResultDTO.success(res.toString());
//            }else{
//                iCommonService.pushMessageToApaas(userDto,agencyVerifyParamVo.getAgencyId(),
//                        agency.getAgencyCode()+"-"+agency.getAgencyName()+"工资指标余额不足");
//                return ApiResultDTO.error(ERROR_RSCODE, "指标余额不足！");
//            }
            remap=service.auditUnitAuditInCommit(agencyids,agencyVerifyParamVo,userDto,false,tokenid);
            if(!StringUtils.isEmpty(remap.get(ERROR_RSCODE))){
                return ApiResultDTO.error(ERROR_RSCODE, agencyInfo.getAgencyName()+remap.get(ERROR_RSCODE).toString());
            }
            return ApiResultDTO.success(remap.get(success));
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, agencyInfo.getAgencyName()+"审核发生异常");

        }
    }




    /**
     * 判断人员发放银行是否与单位对应
     * @param agencyId
     * @return
     */
    @GetMapping("/JudgePersonBank")
    public  ApiResultDTO JudgePersonBank(String agencyId){
        try {
            List<PersonExt> j = null;
            List<PersonExt> personExts = new ArrayList<>();
            AgencyExt agencyExt = new AgencyExt();
            //根据agencyId查询PersonExt表的银行信息
            personExts = service.selectPersonExtByAgencyId(agencyId);
            //根据agencyId查询AgencyExt表的银行信息
            agencyExt = service.selectAgencyExtByAgencyId(agencyId);
            //判断AgencyExt表中单位所选的银行是否包含PersonExt表中单位所有人的银行
            // j=1,代表不包含
            if(StringUtils.isEmpty(agencyExt.getAgencyBankName())){
                return ApiResultDTO.success(null);
            }
            for(int i=0; i<personExts.size(); i++){
                //判断是否存在银行信息不匹配人员 如果有set 一个1  没有set一个0 然后将 1和0 传到前台做处理
                if(!agencyExt.getAgencyBankName().contains(personExts.get(i).getSalaCardBank())){
                    personExts.get(i).setSalaCardBank("1");
                    j = personExts;
                }else {
                    personExts.get(i).setSalaCardBank("0");
                    j = personExts;
                }
            }
            return ApiResultDTO.success(j);
        } catch (Exception e) {
            logger.info("人员银行信息校验失败",e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }


    @GetMapping("/getSubmitAble")
    public ApiResultDTO getSubmitAble(@RequestParam(value = "agencyId") String agencyId) {
        try {
            Integer subnum = service.getSubmitAble(agencyId);
            return ApiResultDTO.success(subnum);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "是否允许上报状态查询失败");
        }
    }
        /**
         * 获取批次数
         * @param agencyId
         * @return
         */

        @GetMapping("/getIsThirteen")
        public ApiResultDTO getIsThirteen(@RequestParam(value = "agencyId") String agencyId) {
            try {
                List<String> isThirteens = service.getIsThirteen(agencyId);
                String isThirteen="";
                if(isThirteens.size() >0){
                    isThirteen=isThirteens.get(0);
                }

                return ApiResultDTO.success(isThirteen);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                return ApiResultDTO.error(ERROR_RSCODE, null);
        }
    }
    /**
     * 判断人员发放银行是否与单位对应
     * @param agencyId
     * @return
     */
    @PostMapping("/addBatch/{agencyId}")
    public ApiResultDTO addBatch(@RequestHeader("tokenid") String tokenid,@PathVariable("agencyId") String agencyId){
        try{
            UserDTO userDto = getUser(tokenid);
            service.addBatch(agencyId,userDto);
            return ApiResultDTO.success(null);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());

        }
    }

    /**
     * 根据单位id获取审核信息
     * @param agencyId
     * @return
     */
    @GetMapping("/getAgencyVerifyByAgencyId/{agencyId}")
    public ApiResultDTO getAgencyVerifyByAgencyId(@PathVariable("agencyId") String agencyId) {
        try{
            AgencyVerify agencyVerify = service.getAgencyVerifyByAgencyId(agencyId);
            return ApiResultDTO.success(agencyVerify);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取审核信息失败");
        }
    }

    @GetMapping("/queryAgencyNameAndState")
    public ApiResultDTO queryAgencyNameAndState(@RequestHeader("tokenid") String tokenid,
                                                @RequestParam(value = "agencyId") String agencyId){
        try {
            //UserDTO userDTO = getUser(tokenid);
            return ApiResultDTO.success(service.getAgencyNameAndState(agencyId));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }


    /**
     * 根据单位id获取BizKey
     * @param agencyId
     * @return
     */
    @GetMapping("/getAgencyVerifyBizKey/{agencyId}")
    public ApiResultDTO getAgencyVerifyBizKey(@PathVariable("agencyId") String agencyId) {
        try{
            AgencyVerify agencyVerify = service.getAgencyVerifyBizKey(agencyId);
            return ApiResultDTO.success(agencyVerify);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取审核信息失败");
        }
    }


    /**
     * 获取实发工资
     * @param agencyId
     * @return
     */
    @GetMapping("/getPaidWagesCount")
    public Integer getPaidWagesCount(@RequestHeader("tokenid") String tokenid,String agencyId){
        try{
            UserDTO userDTO = getUser(tokenid);
            return service.getPaidWagesCount(agencyId,userDTO);
        }catch (Exception e){
            logger.warn(e.getMessage());
            return 10000;
        }
    }
}
